package com.fram.service.admin.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.fram.bean.admin.news.response.NewsListResponse;
import com.fram.bean.sys.PageBean;
import com.fram.common.canstant.ErrCode;
import com.fram.common.exception.ProException;
import com.fram.common.exception.ProValiDataException;
import com.fram.common.util.qiniu.QiniuUtils;
import com.fram.entity.NewsList;
import com.fram.mapper.NewsListMapper;
import com.fram.service.admin.NewsListService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * @作者：大晓刚 @时间 2020年5月19日 @dascription: ->
 */
@Service
public class NewsListServiceImpl implements NewsListService {

	@Autowired
	private NewsListMapper newsListMapper;
	@Autowired
	private QiniuUtils qiniuUtils;

	/** 新增 **/
	@Override
	public void add(NewsList record) throws ProException {
		if (!StringUtils.isEmpty(record.getNewsImg())) {
			record.setNewsImg(qiniuUtils.uploadImageUrl(record.getNewsImg()));
		}
		record.setNewsIntroduce(qiniuUtils.dealHtml(record.getNewsIntroduce(), "1/" + record.getDistributorId() + "/"));
		if (newsListMapper.insertSelective(record) == 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

	/** 查询列表 **/
	@Override
	public PageInfo<NewsListResponse> list(PageBean<NewsList> request) throws ProException {
		//
		PageHelper.startPage(request.getPageNum(), request.getPageSize());
		List<NewsListResponse> list = newsListMapper.selectNewsList(request.getParam());
		if (list == null || list.size() == 0) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return new PageInfo<>(list);
	}

	/** 详情 **/
	@Override
	public NewsList details(Long id) throws ProException {
		NewsList newsList = newsListMapper.selectByPrimaryKey(id);
		if (newsList == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		return newsList;
	}

	/** 修改 **/
	@Override
	public void update(NewsList record) throws ProException {
		NewsList newList = newsListMapper.selectByPrimaryKey(record.getId());
		if (newList == null) {
			throw new ProValiDataException(ErrCode.NO_DATA.getReturnCode(), ErrCode.NO_DATA.getReturnMsg());
		}
		if (!StringUtils.isEmpty(record.getNewsImg())) {
			record.setNewsImg(qiniuUtils.uploadImageUrl(record.getNewsImg()));
		}
		record.setNewsIntroduce(qiniuUtils.dealHtml(record.getNewsIntroduce(), "1/" + newList.getDistributorId() + "/"));
		if (newsListMapper.updateByPrimaryKeySelective(record) == 0) {
			throw new ProValiDataException(ErrCode.FAIL.getReturnCode(), ErrCode.FAIL.getReturnMsg());
		}
	}

}
